<template>
  <div>
    <el-row>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-col :span="12" v-if="isRenewal === '1'">
          <el-form-item label="原商机" prop="parentOrderId">
            <el-select
              @change="paddingOrderData(form.parentOrderId)"
              v-model="form.parentOrderId"
              placeholder="请选择原商机"
              style="width: 100%"
              filterable
            >
              <el-option
                v-for="parentOrder in parentOrderList"
                :key="parentOrder.orderId"
                :label="parentOrder.orderName"
                :value="parentOrder.orderId"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="客户名称" prop="customerId">
            <el-select
              v-model="form.customerId"
              placeholder="请选择客户名称"
              style="width: 100%"
              filterable
            >
              <el-option
                v-for="customer in customerList"
                :key="customer.customerId"
                :label="customer.customerName"
                :value="customer.customerId"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="商机名称" prop="orderName">
            <el-input
              v-model="form.orderName"
              placeholder="请输入商机订单名称"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="商机归属" prop="orderAscription">
            <el-select
              v-model="form.orderAscription"
              style="width: 100%"
              placeholder="请选择商机归属"
              filterable
            >
              <el-option
                v-for="dict in getGroupData()"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="产品类型" prop="productId">
            <el-input
              @focus="openProductDialog"
              v-model="form.productName"
              placeholder="请输入产品类型"
            >
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="产品市场价格">
            <el-input
              readonly
              v-model="form.marketPrice"
              placeholder="产品市场价格"
              type="number"
            >
              <template slot="append">{{
                digitUppercase(form.marketPrice)
              }}</template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="产品出货价格">
            <el-input
              readonly
              v-model="form.shippingPrice"
              placeholder="产品出货价格"
              type="number"
            >
              <template slot="append">{{
                digitUppercase(form.shippingPrice)
              }}</template>
            </el-input>
          </el-form-item>
        </el-col>
        <!-- <el-col :span="12">
          <el-form-item label="商机金额" prop="amount">
            <el-input
              v-model="form.amount"
              placeholder="请输入订单金额"
              type="number"
            >
              <template slot="append">{{
                digitUppercase(form.amount)
              }}</template>
            </el-input>
          </el-form-item>
        </el-col> -->
        <el-col :span="12">
          <el-form-item label="商机预算" prop="budget">
            <el-input
              v-model="form.budget"
              placeholder="请输入预算"
              type="number"
            >
              <template slot="append">{{
                digitUppercase(form.budget)
              }}</template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="项目进度" prop="progess">
            <el-select
              v-model="form.progess"
              placeholder="请选择项目进度"
              style="width: 100%"
            >
              <el-option
                v-for="dict in dict.type.project_progress"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            :label="`${isRenewal === '0' ? '下单' : '续费'}时间`"
            prop="planPurchaseTime"
          >
            <el-date-picker
              clearable
              style="width: 100%"
              v-model="form.planPurchaseTime"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="请选择预计下单时间"
            >
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            :label="`${isRenewal === '0' ? '项目' : '续费'}金额`"
            prop="planAmount"
          >
            <el-input
              v-model="form.planAmount"
              placeholder="请输入预计金额"
              type="number"
            >
              <template slot="append">{{
                digitUppercase(form.planAmount)
              }}</template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12" v-if="isRenewal === '1'">
          <el-form-item label="续费到期时间" prop="renewalEndTime">
            <el-date-picker
              clearable
              style="width: 100%"
              v-model="form.renewalEndTime"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="请选择续费到期时间"
            >
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="客户联系人" prop="contactPerson">
            <el-input
              v-model="form.contactPerson"
              placeholder="请输入客户联系人"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="客户联系电话" prop="clientPhone">
            <el-input
              v-model="form.clientPhone"
              placeholder="请输入客户联系电话"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="集成商" prop="cooperater">
            <el-input v-model="form.cooperater" placeholder="请输入集成商" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="集成商联系人" prop="cooperaterPerson">
            <el-input
              v-model="form.cooperaterPerson"
              placeholder="请输入集成商联系人"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="集成商联系电话" prop="cooperaterPhone">
            <el-input
              v-model="form.cooperaterPhone"
              placeholder="请输入集成商联系电话"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="协同人" prop="helpPerson">
            <el-select
              v-model="form.helpPerson"
              placeholder="请选择协同人"
              style="width: 100%"
              filterable
              clearable
              multiple
            >
              <el-option
                v-for="user in userList"
                :key="user.userId"
                :label="user.userName"
                :value="user.userId"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="项目计划" prop="plan">
            <el-input
              v-model="form.plan"
              type="textarea"
              placeholder="请输入内容"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="沟通情况">
            <el-input
              v-model="form.contactContent"
              type="textarea"
              placeholder="沟通情况"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="备注" prop="remark">
            <el-input
              v-model="form.remark"
              type="textarea"
              placeholder="请输入内容"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24" v-if="!disabled">
          <el-form-item class="dialog-footer">
            <el-button type="primary" @click="submitForm('1')">确 定</el-button>
            <el-button @click="cancel">取 消</el-button>
            <el-button type="info" @click="submitForm('0')" v-if="buttonFlag"
              >暂 存</el-button
            >
          </el-form-item>
        </el-col>
      </el-form>
    </el-row>

    <chooseProduct ref="chooseProduct" @setInfo="settingData"></chooseProduct>
  </div>
</template>

<script>
import {
  getOrder,
  addOrder,
  updateOrder,
  getCrmOrderAllNoPage,
  getOrderOne,
} from "@/api/crm/order";


import chooseProduct from './chooseProduct.vue'
export default {
  name: "addOrUpdateOrder",
  dicts: ["project_type", "project_progress"],
  props: {
    userList: {
      type: Array,
      default: [],
    },
    customerList: {
      type: Array,
      default: [],
    },
    productList: {
      type: Array,
      default: [],
    },
    orderId: {
      type: String,
      default: "",
    },
    isRenewal: {
      type: String,
      default: "0",
    },
    disabled: {
      type: Boolean,
      default: false,
    },
  },
  components: {chooseProduct},
  data() {
    return {
      product: {},
      form: {
        crmOrderProductDiscount: {}
      },
      parentOrderList: [],
      // 表单校验
      rules: {
        parentOrderId: [
          { required: true, message: "原商机不能为空", trigger: "change" },
        ],
        renewalEndTime: [
          {
            required: true,
            message: "续费到期时间不能为空",
            trigger: "change",
          },
        ],
        orderName: [
          { required: true, message: "订单名称不能为空", trigger: "blur" },
        ],
        customerId: [
          { required: true, message: "客户不能为空", trigger: "blur" },
        ],
        amount: [
          { required: true, message: "订单金额不能为空", trigger: "blur" },
        ],
        contactContent: [
          { required: true, message: "不能为空", trigger: "blur" },
        ],
        productId: [{ required: true, message: "不能为空", trigger: "change" }],
        budget: [{ required: true, message: "不能为空", trigger: "blur" }],
        progess: [{ required: true, message: "不能为空", trigger: "blur" }],
        planPurchaseTime: [
          { required: true, message: "不能为空", trigger: "blur" },
        ],
        planAmount: [{ required: true, message: "不能为空", trigger: "blur" }],
        orderAscription: [{ required: true, message: "不能为空", trigger: "change" }]
      },
      buttonFlag: false, // 控制暂存按钮
    };
  },
  created() {},
  watch: {
    orderId: {
      handler(val) {
        // 控制暂存按钮
        this.buttonFlag = this.orderId?.split("_")[0] ? false : true;
        this.reset();
        this.getOrder();
        if(this.isRenewal === '1'){
          this.getCrmOrderAllNoPage();
        }
      },
      deep: true,
      immediate: true,
    },
  },
  methods: {
    getData(){},
    openProductDialog(){
      this.$refs.chooseProduct.open()
    },
    settingData(obj) {
      this.$set(this.form, 'productName', obj.productName);
      this.$set(this.form, 'productId', obj.productId);
      this.$set(this.form, 'marketPrice', obj.marketPrice);
      this.$set(this.form, 'isDiscount', obj.isDiscount);

      if(!this.form.orderName) {
        this.$set(this.form, 'orderName', obj.productName);
      }

      // 如果申请了折扣，则出货价则为折扣后的价格
      if (obj.isDiscount === '0') {
        this.$set(this.form, 'shippingPrice', obj.discountPrice);
        this.$set(this.form, 'amount', obj.discountPrice);
        this.$set(this.form, 'planAmount', obj.discountPrice);
      } else {
        this.$set(this.form, 'shippingPrice', obj.shippingPrice);
        this.$set(this.form, 'amount', obj.shippingPrice);
        this.$set(this.form, 'planAmount', obj.shippingPrice);
      }

      // 更新 crmOrderProductDiscount 对象，保留响应性
      this.form.crmOrderProductDiscount = {
        ...this.form.crmOrderProductDiscount,
        discountId: this.form.crmOrderProductDiscount?.discountId,
        orderId: this.form.orderId,
        productId: this.form.productId,
        discountPrice: obj.discountPrice,
        isDiscount: obj.isDiscount,
        remark: obj.remark,
      };
    },

    paddingOrderData(orderId) {
      let obj = this.parentOrderList.find((item) => item.orderId === orderId);
      this.form.customerId = obj.customerId;
      this.form.orderName = obj.orderName + "_续费_" + new Date().getFullYear();
      this.form.amount = obj.amount;
      this.form.productId = obj.productId;
      this.settingMarketPrice(this.form.productId);

      this.form.isDiscount = '1'
      this.form.budget = obj.budget;
      this.form.contactPerson = obj.contactPerson;
      this.form.clientPhone = obj.clientPhone;
      this.form.cooperater = obj.cooperater;
      this.form.cooperaterPerson = obj.cooperaterPerson;
      this.form.cooperaterPhone = obj.cooperaterPhone;
      this.form.helpPerson = obj.helpPerson ? obj.helpPerson.split(",") : null;
      this.form.plan = obj.plan;
      this.form.contactContent = obj.contactContent;
      this.form.remark = obj.remark;
    },
    getCrmOrderAllNoPage() {
      getCrmOrderAllNoPage({}).then((res) => {
        this.parentOrderList = res.data;
      });
    },
    async getOrder() {
      let id = this.orderId?.split("_")[0];
      if (id) {
        getOrder(id).then((res) => {
          this.form = res.data || {crmOrderProductDiscount: {} };
          this.form.helpPerson = this.form.helpPerson
            ? this.form.helpPerson.split(",")
            : null;
          
          this.settingMarketPrice(this.form.productId);
          // 如果存在产品折扣申请，则把产品折扣后价格覆盖产品的出货价
          if(this.form.crmOrderProductDiscount && this.form.crmOrderProductDiscount.discountPrice){
            this.form.shippingPrice = this.form.crmOrderProductDiscount.discountPrice
          }

        });
      } else {
        getOrderOne({ status: "0", orderType: this.isRenewal }).then((res) => {
          this.form = res.data || { crmOrderProductDiscount: {} };
          if(this.form.helpPerson){
            this.form.helpPerson =  this.form.helpPerson.split(",")
          }       
          this.settingMarketPrice(this.form.productId);

          // 如果存在产品折扣申请，则把产品折扣后价格覆盖产品的出货价
          if(this.form.crmOrderProductDiscount && this.form.crmOrderProductDiscount.discountPrice){
            this.form.shippingPrice = this.form.crmOrderProductDiscount.discountPrice
          }
        });
      }
    },
    settingMarketPrice(productId) {
      this.product = this.productList.find((item) => item.productId === productId) || {};
      this.form.marketPrice = this.product.marketPrice;
      this.form.shippingPrice = this.product.shippingPrice;
      this.form.productName = this.product.productName
    },
    // 表单重置
    reset() {
      this.form = {
        orderId: null,
        orderName: null,
        customerId: null,
        amount: null,
        helpPerson: null,
        contactContent: null,
        type: null,
        budget: null,
        progess: null,
        contactPerson: null,
        clientPhone: null,
        cooperater: null,
        cooperaterPerson: null,
        cooperaterPhone: null,
        plan: null,
        nextFollowupTime: null,
        planPurchaseTime: null,
        status: null,
        planAmount: null,
        renewalTime: null,
        renewalAmount: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        delFlag: null,
        remark: null,
        crmOrderProductDiscount: {}
      };
    },
    // 取消按钮
    cancel() {
      this.reset();
      this.$emit("cancel");
    },
    /** 提交按钮 */
    submitForm(status) {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.form.orderType = this.isRenewal;
          this.form.status = status;
          let obj = {...this.form}
          obj.helpPerson = obj.helpPerson?.join(",");
          if (obj.orderId != null) {
            updateOrder(obj).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.$emit("cancel");
            });
          } else {
            addOrder(obj).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.$emit("cancel");
            });
          }
        }
      });
    },
  },
};
</script>
